<template>
  <div class="analytics-container">
    <!-- 基本信息卡片 -->
    <el-row :gutter="20" class="info-cards">
      <el-col :span="8">
        <el-card>
          <template #header>总点击量</template>
          <div class="card-content">
            {{ stats?.total_clicks || 0 }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <template #header>独立访客</template>
          <div class="card-content">
            {{ stats?.unique_visitors || 0 }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <template #header>转化率</template>
          <div class="card-content">
            {{ conversionRate }}%
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- URL信息 -->
    <el-card class="url-info">
      <template #header>链接信息</template>
      <p><strong>原始链接：</strong>{{ stats?.url_info?.original_url }}</p>
      <p><strong>短链接：</strong>{{ fullShortUrl }}</p>
      <p><strong>创建时间：</strong>{{ formatDate(stats?.url_info?.created_at) }}</p>
      <p v-if="stats?.url_info?.expires_at">
        <strong>过期时间：</strong>{{ formatDate(stats?.url_info?.expires_at) }}
      </p>
    </el-card>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts">
      <el-col :span="24">
        <el-card>
          <template #header>24小时访问趋势</template>
          <div ref="hourlyChartRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts">
      <el-col :span="12">
        <el-card>
          <template #header>浏览器分布</template>
          <div ref="browserChartRef" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>访问者地理分布</template>
          <div ref="locationChartRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts'
import { useShortenerStore } from '../store/shortener'
import dayjs from 'dayjs'

const props = defineProps({
  shortCode: {
    type: String,
    required: true
  }
})

const store = useShortenerStore()
const stats = ref(null)
const hourlyChartRef = ref(null)
const browserChartRef = ref(null)
const locationChartRef = ref(null)
let hourlyChart = null
let browserChart = null
let locationChart = null

const conversionRate = computed(() => {
  if (!stats.value?.total_clicks || !stats.value?.unique_visitors) return 0
  return ((stats.value.unique_visitors / stats.value.total_clicks) * 100).toFixed(2)
})

const fullShortUrl = computed(() => {
  if (!props.shortCode) return ''
  return `http://localhost:8000/${props.shortCode}`
})

const formatDate = (date) => {
  if (!date) return ''
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const initCharts = () => {
  hourlyChart = echarts.init(hourlyChartRef.value)
  browserChart = echarts.init(browserChartRef.value)
  locationChart = echarts.init(locationChartRef.value)
}

const updateHourlyChart = (data) => {
  const hours = Object.keys(data)
  const values = Object.values(data)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: hours.map(h => dayjs(h).format('HH:mm')),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: values,
      type: 'line',
      smooth: true,
      areaStyle: {}
    }]
  }
  
  hourlyChart.setOption(option)
}

const updateBrowserChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      data: Object.entries(data).map(([name, value]) => ({
        name,
        value
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  browserChart.setOption(option)
}

const updateLocationChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '20',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: Object.entries(data).map(([name, value]) => ({
        name,
        value
      }))
    }]
  }
  
  locationChart.setOption(option)
}

const loadData = async () => {
  try {
    stats.value = await store.fetchUrlStats(props.shortCode)
    updateHourlyChart(stats.value.hourly_stats)
    updateBrowserChart(stats.value.browser_stats)
    updateLocationChart(stats.value.location_stats)
  } catch (error) {
    console.error('Failed to load stats:', error)
  }
}

onMounted(() => {
  initCharts()
  loadData()
  
  // 自适应窗口大小
  window.addEventListener('resize', () => {
    hourlyChart?.resize()
    browserChart?.resize()
    locationChart?.resize()
  })
})

watch(() => props.shortCode, () => {
  loadData()
})
</script>

<style scoped>
.analytics-container {
  padding: 20px;
}

.info-cards {
  margin-bottom: 20px;
}

.card-content {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  color: #409EFF;
}

.url-info {
  margin-bottom: 20px;
}

.charts {
  margin-bottom: 20px;
}

.chart {
  height: 300px;
  width: 100%;
}

.el-card {
  margin-bottom: 20px;
}
</style> 